using System;
using System.Linq.Expressions;
using System.Windows;
using System.Windows.Data;
using FluentSilverlight.Utility.Reflection;

namespace FluentSilverlight.Expressions
{
    public class PropertyBinder<TModel>
    {
        private readonly FrameworkElement element;

        public PropertyBinder(FrameworkElement element)
        {
            this.element = element;
        }

        public void SetBindingWithConversion<TValueConverter>(Expression<Func<TModel, object>> expression, DependencyProperty property)
            where TValueConverter : IValueConverter, new()
        {
            SetBinding(expression, property, BindingMode.OneWay, new TValueConverter());
        }

        public void SetBinding(Expression<Func<TModel, object>> expression, DependencyProperty property)
        {
            SetBinding(expression, property, BindingMode.OneWay);
        }

        public void SetBinding(Expression<Func<TModel, object>> expression, DependencyProperty property,
                               BindingMode bindingMode)
        {
            SetBinding(expression, property, bindingMode, null);
        }

        public void SetBinding(Expression<Func<TModel, object>> expression, DependencyProperty property,
                               BindingMode bindingMode, IValueConverter valueConverter)
        {
            if (expression == null) return;

            var accessor = ReflectionHelper.GetAccessor(expression);
            var binding = new Binding(accessor.Name) { Mode = bindingMode };
            if (valueConverter != null) binding.Converter = valueConverter;
            element.SetBinding(property, binding);                
        }
    }
}